from common.models.member import MemberComment
from common.libs.UrlManager import UrlManager
from common.libs.Helper import selectFilterObj
from common.libs.Helper import getDictFilterFiled
from common.libs.Helper import getCurrentDate
from common.models.member import MemberAddress
from web.controllers.api import route_api
from common.models.pay import PayOrderItem
from common.models.pay import PayOrder
from common.models.food import Food
from common.models.member import Member

from flask import request, g
from flask import jsonify
import json

@route_api.route('/my/info')
def myInfo():
    result = {'code': 200, 'msg': '操作成功', 'data': {}}
    current_member = g.current_member
    if current_member:
        member = Member.query.filter_by(id=current_member.id).first()
        user_info = {
            'nickname': member.nickname,
            'avatar_url': member.avatar
        }
        result['data']['user_info'] = user_info
    return jsonify(result)

@route_api.route('/my/order')
def myOrder():
    """
    我的订单列表展示
    :return:
    """
    result = {'code': 200, 'msg': '操作成功', 'data': {}}
    order_list = []
    resp = request.values
    status = resp.get('status')
    current_member = g.current_member
    if not current_member:
        result['code'] = -1
        result['msg'] = '请先登入！'
        return jsonify(result)
    query = PayOrder.query.filter(PayOrder.member_id == current_member.id)

    if status == '-8':  # 待付款
        query = query.filter(
            PayOrder.status == -8
        )
    elif status == '-7':  # 待发货
        query = query.filter(
            PayOrder.status == 1,
            PayOrder.express_status == -7,
            PayOrder.comment_status == 0
        )
    elif status == '-6':  # 待收货
        query = query.filter(
            PayOrder.status == 1,
            PayOrder.express_status == -6,
            PayOrder.comment_status == 0
        )
    elif status == '-5':  # 待评价
        query = query.filter(
            PayOrder.status == 1,
            PayOrder.express_status == 1,
            PayOrder.comment_status == 0
        )
    elif status == '1':  # 已完成
        query = query.filter(
            PayOrder.status == 1,
            PayOrder.express_status == 1,
            PayOrder.comment_status == 1
        )
    else:  # 已关闭
        query = query.filter(
            PayOrder.status == 0
        )

    pay_order_list = query.order_by(PayOrder.id.desc())
    # 先获取订单列表的id
    pay_order_ids = selectFilterObj(pay_order_list, 'id')
    # 根据订单列表的id查询出对应的订单详情
    pay_order_item_list = PayOrderItem.query.filter(PayOrderItem.pay_order_id.in_(pay_order_ids))
    # 根据订单详情，获取对应食物的id
    pay_food_ids = selectFilterObj(pay_order_item_list, 'food_id')
    # 根据食物的id生成对应的事物id和对象的映射字典
    foods_mapping = getDictFilterFiled(Food, Food.id, 'id', pay_food_ids)

    pay_order_item_mapping = {}
    if pay_order_item_list:
        for item in pay_order_item_list:
            # 该判断避免键值重复
            if item.pay_order_id not in pay_order_item_mapping:
                pay_order_item_mapping[item.pay_order_id] = []
            # 根据食品的id和映射字典获取对应的食品对象
            temp_food_info = foods_mapping[item.food_id]
            pay_order_item_mapping[item.pay_order_id].append({
                'id': item.id,  # 订单详情的id
                'food_id': item.food_id,  # 详情订单中食物的id
                'quantity': item.quantity,  # 详情订单中食物的数量
                'pic_url': UrlManager.buildImageUrl(temp_food_info.main_image)
            })
    for pay_order in pay_order_list:
        res = {
            'id':pay_order.id,
            'status': pay_order.pay_status,
            'status_desc': pay_order.status_desc,
            'date': pay_order.created_time.strftime('%Y-%m-%d %H:%M:%S'),
            'order_number': pay_order.order_sn,
            'note': pay_order.note,
            'total_price': str(pay_order.total_price),
            'goods_list': pay_order_item_mapping[pay_order.id]
        }
        order_list.append(res)
    result['data']['order_list'] = order_list
    return jsonify(result)

@route_api.route('/my/comment/set', methods=['POST'])
def myCommentSet():
    result = {'code': 200, 'msg': '操作成功', 'data': {}}
    resp = request.values
    content = resp.get('content')
    score = resp.get('score', type=float)
    order_sn = resp.get('order_sn')

    current_member = g.current_member
    if not current_member:
        result['code'] = -1
        result['msg'] = '请先登入'
        return jsonify(result)

    order_info = PayOrder.query.filter_by(
        member_id=current_member.id, order_sn=order_sn).first()

    if not order_info:
        result['code'] = -1
        result['msg'] = '业务繁忙，请稍后再操作哦~~'
        return jsonify(result)

    items = PayOrderItem.query.filter_by(pay_order_id=order_info.id).all()
    food_ids = selectFilterObj(items,'food_id')
    food_mapping =getDictFilterFiled(Food,Food.id,'id',food_ids)
    # 修改美食的评论数
    for item in items:
        temp_food = food_mapping[item.food_id]
        temp_food.comment_count += 1
        temp_food.update()

    model_comment = MemberComment()
    model_comment.member_id = current_member.id
    model_comment.food_ids = json.dumps(food_ids)
    model_comment.pay_order_id = order_info.id
    model_comment.score = score
    model_comment.content = content
    model_comment.created_time = getCurrentDate()
    model_comment.save()

    # 修改订单的评论状态
    order_info.comment_status = 1
    order_info.updated_time = getCurrentDate()
    order_info.update()

    return jsonify(result)

@route_api.route('/my/comment')
def myComment():
    result = {'code': 200, 'msg': '操作成功', 'data': {}}
    list = []
    current_member = g.current_member
    if not current_member:
        result['code'] = -1
        result['msg'] = '请先登入'
        return jsonify(result)
    comment_list = MemberComment.query.filter(MemberComment.member_id==current_member.id)\
        .order_by(MemberComment.id.desc()).all()
    pay_order_mapping = getDictFilterFiled(PayOrder, PayOrder.member_id, 'id', [current_member.id])
    if comment_list:
        for comment in comment_list:
            res = {
                'date': comment.created_time.strftime('%Y-%m-%d %H:%M:%S'),
                'order_number': pay_order_mapping[comment.pay_order_id].order_sn,
                'content': comment.content,
            }
            list.append(res)

    result['data']['list'] = list
    return jsonify(result)



